<template>
  <div class="hello">
    <canvas id="canvas1"></canvas>
    <br /><br />
    fasdfda
    <input type="button" value="保存png图片" id="btn1" @click="download()"/>
    <input type="button" value="保存jpg图片" id="btn2" />
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      canvas: undefined
    }
  },
  mounted () {
    this.canvas = document.getElementById('canvas1');
    var ctx = this.canvas.getContext('2d');
    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    ctx.fillStyle = 'red';
    ctx.font = 'italic bold 30px Helvetica ';
    ctx.fillText('楷体', 50, 50);
  },
  methods: {
    download () {
      let type = 'png'
      var imgdata = this.canvas.toDataURL(type);
      // 将mime-type改为image/octet-stream,强制让浏览器下载
      var fixtype = function (type) {
          type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
          var r = type.match(/png|jpeg|bmp|gif/)[0];
          return 'image/' + r;
      }
      imgdata = imgdata.replace(fixtype(type), 'image/octet-stream')
      // 将图片保存到本地
      var saveFile = function (data, filename) {
          var link = document.createElement('a');
          link.href = data;
          link.download = filename;
          var event = document.createEvent('MouseEvents');
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
          link.dispatchEvent(event);
      }
      var filename = 'test2017' + '.' + type;
      saveFile(imgdata, filename);
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
